import Card from '@/components/Card';
import Description from '@/components/Description';
import { stationControllerEditStation as edit } from '@/services/ess/station';
import { DATABASE_TYPE_ENUM, fetchDictInfo } from '@/utils';
import { useIntl } from '@umijs/max';
import { Modal } from 'antd';
import React, { useEffect, useState } from 'react';
const { confirm } = Modal;

const BaseInfo: React.FC<{
  detailInfo: API.StationInfo | null;
}> = ({ detailInfo }) => {
  const intl = useIntl();
  const [stationRunStatusOptions, setStationRunStatusOptions] = useState<
    { label: string; value: string | number }[]
  >([]);

  useEffect(() => {
    fetchDictInfo(DATABASE_TYPE_ENUM.STATION_RUN_STATUS, true).then((res) => {
      setStationRunStatusOptions(res ?? []);
    });
  }, []);

  const [items, setItems] = useState<
    Array<{
      key: string;
      label: string;
      children: React.ReactNode;
      span?: number;
      isSelect?: boolean;
      selectOptions?: { label: string; value: string | number }[];
      onChange?: (value: string | number) => void;
    }>
  >([
    {
      key: 'createTime',
      label: intl.formatMessage({ id: 'siteManage.createTime' }),
      children: '',
    },
    {
      key: 'modifyTime',
      label: intl.formatMessage({ id: 'siteManage.updateTime' }),
      children: '',
    },
    {
      key: 'stationName',
      label: intl.formatMessage({ id: 'siteManage.plantName' }),
      children: '',
    },
    {
      key: 'stationNo',
      label: intl.formatMessage({ id: 'siteManage.plantCode' }),
      children: '',
    },
    {
      key: 'tenantName',
      label: intl.formatMessage({ id: 'siteManage.tenantName' }),
      children: '',
    },
    {
      key: 'stationType',
      label: intl.formatMessage({ id: 'siteManage.plantType' }),
      children: '',
      span: 1,
    },
    {
      key: 'runStatus',
      label: intl.formatMessage({ id: 'siteManage.opStatus' }),
      children: '',
      span: 1,
      isSelect: true,
      selectOptions: [],
    },
    {
      key: 'status',
      label: intl.formatMessage({ id: 'siteManage.plantStatus' }),
      children: '',
      span: 1,
    },
  ]);

  const [siteTypes, setSiteTypes] = useState<Array<{ value: string; label: string }>>([]);

  useEffect(() => {
    fetchDictInfo(DATABASE_TYPE_ENUM.SITE_TYPE).then((res) => {
      setSiteTypes(res || []);
    });
  }, []);

  useEffect(() => {
    if (detailInfo && detailInfo.id) {
      const result = items.map((item) => {
        const newItem = { ...item };
        if (item.key === 'stationType') {
          newItem.children =
            siteTypes.find((row) => row.value === detailInfo.stationType)?.label || '';
        } else if (item.key === 'runStatus') {
          const runStatusLabel = stationRunStatusOptions.find(
            (option) => option.value === detailInfo.runStatus,
          )?.value;
          newItem.children = runStatusLabel || '';
          newItem.selectOptions = stationRunStatusOptions;
        } else if (item.key === 'status') {
          newItem.children =
            detailInfo.status === 1
              ? intl.formatMessage({ id: 'systemManagement.generalProcedure.enable' })
              : intl.formatMessage({ id: 'systemManagement.generalProcedure.disable' });
        } else {
          // @ts-ignore
          newItem.children = detailInfo[item.key as keyof API.StationInfo];
        }
        return newItem;
      });
      setItems(result);
    }
  }, [detailInfo, siteTypes, stationRunStatusOptions]);

  const handleRunStatusChange = async (value: string | number) => {
    if (!detailInfo) return;

    const selectedOption = stationRunStatusOptions.find((option) => option.value === value);
    if (!selectedOption) return;

    confirm({
      title: intl.formatMessage({ id: 'systemManagement.supplementary.prompt' }),
      content: `${intl.formatMessage({ id: 'siteManage.changeStatus' })}${selectedOption.label}？`,
      onOk: async () => {
        const payload = {
          id: detailInfo.id,
          runStatus: value,
          tenantId: detailInfo.tenantId,
          stationType: detailInfo.stationType,
          stationNo: detailInfo.stationNo,
          stationName: detailInfo.stationName,
          contactName: detailInfo.contactName,
          contactPhone: detailInfo.contactPhone,
          status: detailInfo.status,
        };

        try {
          await edit(payload as API.StationReq);
          // 更新本地状态
          setItems((prevItems) =>
            prevItems.map((item) =>
              item.key === 'runStatus' ? { ...item, children: value } : item,
            ),
          );
          // 如果需要刷新整个页面数据，可以在这里添加相应的逻辑
          // 例如：actionRef.current?.reloadAndRest?.();
        } catch (error) {
          console.error('Failed to update run status:', error);
        }
      },
    });
  };

  return (
    <Card title={intl.formatMessage({ id: 'siteManage.basePlantInfo' })}>
      <Description items={items} onRunStatusChange={handleRunStatusChange} />
    </Card>
  );
};

export default BaseInfo;
